package org.fao.pims.web.references;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.List;
import org.apache.commons.logging.*;
import org.apache.struts.action.*;
import org.fao.pims.model.*;
import org.fao.pims.service.references.*;

public class ReferencesAction extends Action {

	private static Log log = LogFactory.getLog(ReferencesAction.class);
	
	public ActionForward execute(
			ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception
	{
		
		ReferencesForm refForm = (ReferencesForm)form;
		String plantName = refForm.getPlantName();
		String animalName = refForm.getAnimalName();
		String authorName = refForm.getAuthorName();

		List refList = null;
		ReferencesManager service = new ReferencesManagerImpl();
		
		try {
			if (plantName != null && plantName != "")
				refList = service.getReferencesByPlant(plantName);
			else if (animalName != null && animalName != "")
				refList = service.getReferencesByAnimal(animalName);
			else
				refList = service.getReferencesByAuthor(authorName);
			
			request.setAttribute("references", refList);						
			
			if( refList.size() > 0 ) {
				request.setAttribute("noResults", "false");						
				return mapping.findForward("success");
			}
			else {
				request.setAttribute("noResults", "true");						
				return mapping.findForward("failure");
			}
		}
		catch(ReferencesException pne) {
			
			System.out.println(pne.getMessage());
			
			ActionMessages errors = new ActionMessages();
			
			errors.add(ActionMessages.GLOBAL_MESSAGE,
                       new ActionMessage("references.sql.exception"));
			this.saveErrors(request, errors);
			return mapping.findForward("failure");
		}
	}

}
